<template>
	<view>
		<view class="padding">
			<view class="money">
				<view class="money-top">
					<image src="../../static/images/me/moneyBanner.png" mode=""></image>
					<view class="money-top-title">
						当前瓜币余额
					</view>
				<!-- 	<view class="money-top-money">
						{{formatNumber(moneyNum)}}
					</view> -->
					<view class="money-top-money">
					{{ moneyNum }}
					</view>
					<view class="regulation" v-if="osname != 'ios'">
						1元兑换100瓜币
					</view>
					<view class="regulation" v-else>
						1钻兑换10瓜币
					</view>
				</view>
				<view @click="goNav('/me/wallet/mingxi')" class="money-bto flex align-center justify-between">
					余额明细
					<u-icon name="arrow-right" color="#6696ff" size="40"></u-icon>
				</view>

			</view>

			<u-radio-group v-model="money">
				<view v-if="wallet.length>0" style="margin-top: 20rpx;border-radius: 24rpx;"
					class=" bg flex justify-between flex-wrap padding-lr padding-bottom">
					<view v-for="(item,index) in wallet" :key='index' class="flex radius margin-top justify-center"
						style="background: #f5f5f5;color: #000; width: 48%;padding: 30rpx 30rpx;border: 1px solid #f5f5f5;">
						<view style="font-size: 24upx;width: 100%;">
							<view class="flex align-center justify-between" style="width: 100%;font-size: 30rpx;">
								<view class="">
										<text style="display: block;text-align: center;" v-if="osname != 'ios'">
											{{item.rmb}}元
										</text>
										<text style="display: block;text-align: center;" v-else>
											{{item.diamond}}钻
										</text>
										<text style="display: block;margin: 5px 0;">{{item.money}}充值瓜币</text>
										<text v-if="item.giveMoney != 0" style="display: block;">{{item.giveMoney}}赠送瓜币</text>
								</view>

								<u-radio :name="item.feeTempItemId"></u-radio>
							</view>
						</view>
					</view>
				</view>
			</u-radio-group>
		<!-- 	<view class="inputMoney">
				<view class="inputMoney-box flex align-center justify-center">
					<u-input input-align="center" placeholder="请输入自定义瓜币" v-model="money" type="number"
						:border="false" />

				</view>
			</view> -->

		<!-- 	<view style="margin: 10rpx auto;">
						<button
						  open-type="im"
						  :data-im-id="imId"
						  @im="imCallback"
						  @error="onimError"
						  style="
							height: 33px;
							background-color: #5173F8;
							color: #FFFFFF;
							font-size: 14px;
							margin:10px"
						>
						  联系客服 9:00~22:00
						</button>
				</view> -->
				<view style="margin: 10rpx auto;margin: 5px auto;position: fixed;bottom: 10%;right: 0;">
							<button
							  open-type="im"
							  :data-im-id="imId"
							  @im="imCallback"
							  @error="onimError"
							  style="
								background-color: rgb(94 97 109 / 57%);
								color: #FFFFFF;
								font-size: 12px;
								height: 60px;
								width: 75px;
								padding: 0;"

							>
							<view class="">
								<u-icon name="server-man" color="#fff" size="28"> </u-icon>
								<text style="margin: 0 5px;">客服</text>
							</view>

							  <text style="display: block;font-size: 9px;">9:00~22:00</text>
							</button>
					</view>

			<view style="padding: 15rpx;display: grid;color: #999;font-size: 12px;" class="">
				<!-- <text style="color: #332f2f;">充值代表接受<text><<充值规则协议>></text> 和 <text @click="goNav('/me/wallet/agreement')"><<会员服务协议>></text></text> -->
				<text style="margin-top: 20rpx;margin-bottom: 10rpx;">温馨提示:</text>
				<text >1.充值及赠送瓜币仅限当前账户在本小程序使用，充值后即可直接观看付费内容。</text>
				<text >2.充值瓜币永久有效,充值多送。</text>
				<text >3.若发现充值未到账,请先确认你登录的账号与充值的账号是否一致。</text>
				<text >4.充值瓜币为虚拟货币,不支持无理由退款，法律或协议另有规定的除外。</text>
				<text >5.未满18周岁的未成年人禁止进行充值。</text>

			</view>
			<view class="bg margin-top padding-lr radius">
				<view>
					<view class="flex align-center justify-between" style="height: 100upx;padding: 20upx 0;"
						v-for="(item,index) in openLists" :key='index'>
						<view class="flex align-center">
							<image :src="item.image" style="width: 55upx;height: 55upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;">{{item.text}}
							</view>
						</view>

						<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
							<label class="tui-radio">
								<radio color="#6696FF" :checked="openWay === item.id ? true : false" />
							</label>
						</radio-group>
					</view>
				</view>
			</view>
			<!-- <view class="btn" @click="pay">确认支付</view> -->
		</view>
		<view class="sumbit flex align-center justify-center">
			<view class="sumbit-box flex align-center justify-center" @click="pay">
				确认支付
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				openLists: [],
				openWay: 1,
				wallet: [],
				money: '',
				placeholder: '',
				moneyNum: 0,
				osname:'',
				imId:'chiguakefu',
				osname:'',
				channelNo:''
			}
		},
		onLoad() {
			this.osname = uni.getStorageSync('osName')
			// this.getwalletList() //获取充值列表 
			// #ifdef APP-PLUS
			this.openLists = [{
				image: '/static/images/pay/weixin.png',
				text: '微信',
				id: 2
			}, {
				image: '/static/images/pay/zhifubao.png',
				text: '支付宝',
				id: 1
			}];
			this.openWay = 2;
			// #endif

			// #ifdef MP-WEIXIN
			this.openLists = [{
				image: '/static/images/pay/weixin.png',
				text: '微信',
				id: 2
			}];
			this.openWay = 2;
			// #endif

			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase();
			if (ua.indexOf('micromessenger') !== -1) {
				this.openLists = [{
					image: '/static/images/pay/weixin.png',
					text: '微信',
					id: 2
				}, {
					image: '/static/images/pay/zhifubao.png',
					text: '支付宝',
					id: 1
				}];
				this.openWay = 2;
			} else {
				this.openLists = [{
					image: '/static/images/pay/zhifubao.png',
					text: '支付宝',
					id: 1
				}];
				this.openWay = 1;
			}
			// #endif
			if(uni.getStorageSync('channel_no')){
				this.channelNo = uni.getStorageSync('channel_no')
			}
		},
		onShow() {
			this.osname = uni.getStorageSync('osName')
			console.log(uni.getStorageSync('osname'),'asdasdasdasasfdsa')
			this.getMyMoney()
			// this.getMoneyList()
			this.getEffectRechargeList()
			const systemInfo = wx.getSystemInfoSync();
			console.log(systemInfo,'------------------');
		},
		methods: {
			//最新获取充值列表模版
			getEffectRechargeList(){
				this.$Request.get('/app/feeTemp/getEffectRechargeList').then(res=>{
						this.wallet = res.data
				})

			},
			// handleInput(e) {
			//       e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
			// 	  console.log(e,'1111111111111')
			// 	   this.$nextTick(() => {
			// 		  for(var i=0;i<this.money.length;i++){
			// 			  this.money[i].value=e
			// 		  }
			// 	  })
			//     },
			imCallback(e) {
			  console.log("跳转IM客服成功", e.detail);
			},
			onimError(e) {
							  console.log(this.imId)
			  console.log("拉起IM客服失败", e.detail);
			},
			/**
			 * 获取充值列表
			 */
			getMoneyList() {
				this.$Request.get('/app/common/type/245').then(res => {
					if (res.code == 0) {
						let arr = []
						res.data.value.split(',').map((item, index) => {
							let obj = {
								money: Number(item),
								id: index + 1
							}
							arr.push(obj)
						})
						this.wallet = arr
					}
				});
			},
			/**
			 * @param {Number} num
			 * @param 保留两位小数
			 */
			formatNumber(num) {
				// 判断是否为整数
				if (Number.isInteger(num)) {
					return num.toFixed(2);
				} else {
					return num.toFixed(2).replace(/\.?0+$/, '');
				}
			},
			/**
			 * 获取余额
			 */
			getMyMoney() {
				this.$Request.getT('/app/moneyDetails/selectUserMoney').then(res => {
					if (res.code == 0) {
						this.moneyNum = 0
						res.data.map(item => {
							this.moneyNum += item.money
						})


						// this.moneyNum = res.data.money
						// this.$Request.getT('/app/invite/selectInviteMoney').then(ret => {
						// 	if (ret.code == 0) {
						// 		if (ret.data.inviteMoney && ret.data.inviteMoney.money) {
						// 			this.moneyNum = Number(res.data.money) + Number(ret.data.inviteMoney
						// 				.money)
						// 		} else {
						// 			res.data.map(item=>{
						// 				if(item.type == 1){
						// 						this.moneyNum = Number(item.money)
						// 				}
						// 				return item
						// 			})
						// 			// this.moneyNum = Number(res.data.money)
						// 		}
						// 	}
						// })
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			goChat() {
				let that = this
				// #ifdef MP-WEIXIN
				wx.openCustomerServiceChat({
					extInfo: {
						url: that.$queue.getData('kefuq')
					},
					corpId: that.$queue.getData('kefuAppidq'),
					success(res) {
						console.log(res)
					},
				})
				// #endif
				// #ifdef H5
				window.location.href = that.$queue.getData('kefuq');
				// #endif
				// #ifdef APP
				let kefu = that.$queue.getData('kefuq')
				console.log(kefu)
				plus.runtime.openURL(kefu, function(res) {});
				// #endif
			},
			input(e) {
				console.log(e)
				this.tabIndex = -1
				this.money = e
			},
			//获取充值列表 
			getwalletList() {
				this.$Request.get("/app/payClassify/selectPayClassifyList").then(res => {
					if (res.code == 0) {
						this.wallet = res.data
					}
				});
			},
			goNav(url) {
				uni.navigateTo({
					url
				})
			},
			selectWay: function(item) {
				this.openWay = item.id;
			},

			pay() {
				if (this.money == 0 || this.money == '') {
					uni.showToast({
						title: '请选择充值或输入充值瓜币',
						icon: 'none'
					})
					return
				}
				// if(this.osname == 'ios'){
				// 		if(this.money % 10 != 0){
				// 			uni.showToast({
				// 				title: '瓜币充值只能为整数（例:10,30,50,100）',
				// 				icon: 'none'
				// 			})
				// 			return
				// 		}
				// }
				if (this.openWay == 2) {
					// #ifdef APP-PLUS
					// 微信APP支付 根据订单id获取支付信息
					this.$Request.postT("/app/douyinPay/payMoney", {
						classify: 1,
						money: this.money,
					}).then(ret => {
						this.isCheckPay(ret.code, 'wxpay', JSON.stringify(ret.data));
					});
					// #endif

					// #ifdef MP-WEIXIN
					// 微信小程序支付
					this.$Request.postT('/app/douyinPay/payMoney', {
						classify: 3,
						money: this.money,
					}).then(ret => {
						uni.hideLoading()
						console.log(ret.data)
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: ret.data.timestamp,
							nonceStr: ret.data.noncestr,
							package: ret.data.package,
							signType: ret.data.signType,
							paySign: ret.data.sign,
							success: function(suc) {
								console.log('success:' + JSON.stringify(suc));
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								})
								setTimeout(d => {
									uni.navigateBack(1)
								}, 1000);
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								})
							}
						});
					});
					// #endif

					// #ifdef H5
					let ua = navigator.userAgent.toLowerCase();
					if (ua.indexOf('micromessenger') !== -1) {
						let data = {
							classify: 2,
							money: this.money,
						}
						this.$Request.postT('/app/douyinPay/payMoney', data).then(res => {
							if (res.code == 0) {
								this.callPay(res.data);
							} else {
								uni.showToast({
									icon: 'none',
									title: '支付失败!'
								});
							}
						});
					}
					// #endif

				} else {

					// APP支付宝支付
					// #ifdef APP

					this.$Request.postT("/app/douyinPay/payMoney", {
						classify: 1,
						money: this.money
					}).then(ret => {
						console.log(ret)
						this.isCheckPay(ret.code, 'alipay', ret.data);
					});
					//抖音小程序支付
					// #endif
					// this.$Request.postT("/app/douyinPay/payMoney", {
					// 	classify: 6,
					// 	money: this.money,
					// 	description:'充值' + this.money + '元'
					// }).then(ret => {
					// 	console.log(ret)
					// 	this.isCheckPay(ret.code, 'alipay', ret.data);
					// });
					const systemInfo = uni.getSystemInfoSync();
					let url = '/app/douyinPay/commonTrade/payMoney?feeTempItemId=' + this.money + '&classify=6' + '&plateform=' + systemInfo.platform;
					if(this.channelNo){
						url = url +'&channelNo='+this.channelNo;
					}
					this.$u.post(url).then(red => {
						if (red.code === 0) {
							tt.login({
								force: true,
								success: (o) => {
									tt.requestOrder({
										data: red.data,
										byteAuthorization: red.byteAuthorization,
										success: (payRes) => {
											tt.getOrderPayment({
												orderId: payRes.orderId,
												success: () => {
													this.getMyMoney()
													//回传
													try {
														const clickid = uni.getStorageSync("ad_clickid")
														if (!!clickid) {
															let walletFilters = this.wallet.filter(w => w.feeTempItemId == this.money)
															let reqBody = {
																"event_type": "successful_pay", 
																"context": {
																	"ad": {
																		"callback": clickid
																	}
																},
																"timestamp": new Date().getTime()
															}
															this.$u.post('app/conversion/doConversion', reqBody)


															let reqBody2 = {
																"event_type": "active_pay", 
																"context": {
																	"ad": {
																		"callback": clickid
																	}
																},
																properties: {
																	"pay_amount": walletFilters[0].rmb * 100
																},
																"timestamp": new Date().getTime()
															}
															this.$u.post('app/conversion/doConversion', reqBody2)
														}
													} catch (e) {

													}
												}
											})
										},
										fail: (err)=> {
										}
									})
								}
							})

						} else {
							uni.showToast({
								icon: 'none',
								title: '支付失败!'
							});
						}
					})
					// #ifdef H5
					let data = {
						classify: 2,
						money: this.money
					}
					this.$Request.postT('/app/douyinPay/payMoney', data).then(
						res => {
							if (res.code === 0) {
								const div = document.createElement('div')
								div.innerHTML = res.data //此处form就是后台返回接收到的数据
								document.body.appendChild(div)
								document.forms[0].submit()
							} else {
								uni.showToast({
									icon: 'none',
									title: '支付失败!'
								});
							}
						});
					// #endif
				}
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				console.log(response, '++++++++')
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						console.log(res, '/*-/*-/*-')
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(status, name, order) {
				if (status == 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误',
						icon: 'none'
					});
				}
			},
			setPayment(name, order) {
				console.log('*-*-*')
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					service:5,
					// getOrderStatus:
					success: function(res) {
						console.log(res)
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			// 提现
			cashMoney() {
				if (!this.moneyNum) {
					uni.showToast({
						icon: 'none',
						title: '请输入提现金额'
					})
					return
				}
				if (this.moneyNum > this.money * 1) {
					uni.showToast({
						icon: 'none',
						title: '您的余额不足'
					})
					return
				}
				// if (this.moneyNum*1+this.charge*this.moneyNum > this.money*1) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '您的手续费不足'
				// 	})
				// 	return
				// }

				let zhiFuBao = uni.getStorageSync('zhiFuBao')
				let zhiFuBaoName = uni.getStorageSync('zhiFuBaoName')

				if (!zhiFuBao && !zhiFuBaoName) {
					uni.navigateTo({
						url: '/my/wallet/zhifubao'
					})
					return
				}

				let that = this
				that.sp = (that.moneyNum * this.charge).toFixed(2)
				uni.showModal({
					title: '提示',
					content: '本次提现' + that.moneyNum + '元，服务费' + this.sp + '元，是否确认提现？',
					success: function(res) {
						if (res.confirm) {
							that.$Request.get("/app/cash/cashMoney", {
								money: that.moneyNum
							}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										icon: 'none',
										title: res.msg
									})
									that.moneyNum = null
								} else {
									uni.showToast({
										icon: 'none',
										title: res.msg
									})
								}
								that.getMoney()
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F7F7;
	}

	.inputMoney {
		width: 100%;
		background-color: #FFFFFF;
		margin-top: 20rpx;
		border-radius: 24rpx;

		.inputMoney-box {
			padding: 30rpx 20rpx;
		}
	}

	.sumbit {
		width: 100%;
		height: 140rpx;
		background-color: #FFFFFF;
		position: fixed;
		bottom: 0;
		left: 0;

		.sumbit-box {
			width: 686rpx;
			height: 88rpx;
			background: #6696FF;
			border-radius: 44rpx;
			color: #FFFFFF;
			font-weight: bold;
		}
	}

	.money {
		width: 100%;
		height: 100%;
		border-radius: 32rpx;
		background-color: #FFFFFF;

		.money-top {
			width: 100%;
			height: 240rpx;
			position: relative;

			image {
				width: 100%;
				height: 100%;
				border-radius: 32rpx 32rpx 0 0;
			}

			.money-top-title {
				position: absolute;
				font-size: 32rpx;
				color: hsla(0, 0%, 100%, .9);
				top: 40rpx;
				left: 40rpx;

			}

			.money-top-money {
				position: absolute;
				font-size: 64rpx;
				font-weight: 500;
				color: #FFFFFF;
				top: 120rpx;
				left: 40rpx;
			}
		}

		.money-bto {
			width: 100%;
			height: 108rpx;
			border-radius: 0 0 32rpx 32rpx;
			padding: 0 30rpx;
			color: #2e2f33;
			font-weight: bold;
		}
	}

	.bg {
		background-color: #FFFFFF;
	}

	.title_btn {
		height: 78upx;
		line-height: 78upx;
		/* background: #f7f7f7; */
	}

	.btn {
		width: 100%;
		height: 88upx;
		background: #6696FF;
		border-radius: 44upx;
		text-align: center;
		line-height: 88upx;
		margin-top: 40upx;
		font-size: 28upx;
		color: #FFF;
	}
	.regulation{
		position: absolute;
		    right: 14px;
		    bottom: 15px;
		    color: #fff;
	}
</style>
